// import TTable, { TTd ,TTh, TTr } from 't/basic/table';

import useMappingProps from 't/common/hooks/useMappingProps';
import { useI18n } from 'vue-i18n';
import {
  commonProps,
  pickOwnForBasicComponent,
  SymbolDestructuring,
} from 't/common/utils';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  ref,
  reactive,
  watch,
  nextTick,
  onBeforeMount,
  onMounted,
} from 'vue';
import './index.scss';

import {
  propsSuffix,
  pickProps,
  mappingEvent,
} from 't/bussiness/mixed-view/utils';

import { useQuasar } from '@teld/q-components';
import TDialog from 't/basic/dialog';
import TButton from 't/basic/button';
import TQuickFilter from 't/bussiness/quick-filter';
import TIcon from 't/basic/icon';

import TLabel from 't/basic/label';
import TToggle from 't/basic/toggle';

import DefaultFilter from './components/default-filter.jsx';

import {
  FilterFieldValueRange,
  FilterFieldDisplayType,
  setHelpTipBase,
} from 't/bussiness/quick-filter/use-quick-filter';

import _ from 'lodash';
import { useUserProfile } from './useUserProfile';

const C_Emits = {
  Confirm: 'confirm',
  Init: 'init',
  Cancel: 'cancel',
  UserProfileChange: 'userProfileChange',
};

const C_TQuickFilter_Emits_Suffix = '';


export default defineComponent({
  name: 'TPopupFilter',
  directives: {
    removeTabindex: {
      mounted(el) {
        // 移除 tabindex 属性
        el?.removeAttribute('tabindex');
      },
    },
  },
  props: {
    // filterFields: { type: Array, default: () => [] },
    // value: {
    //   type: [Object, Array],
    //   default() {
    //     return [{ code: 'F1', value: [] }];
    //   },
    // },
    // schema: {
    //   type: Array,
    //   default() {
    //     return [];
    //   },
    // },
    // value: {
    //   type: Object,
    //   default() {
    //     return {};
    //   },
    // },
    ...TQuickFilter.props,
    // filterFields: { type: Array, default: () => [1,2,3] },
    hideQuickFilter: {
      type: Boolean,
      default: false,
    },
    bgColor: {
      type: String,
      default: '#fff',
    },
    hidePopupFilter: {
      type: Boolean,
      default: false,
    },
    filterText: {
      type: String,
      default: '',
    },
    filterIcon: {
      type: String,
      default: 'fas dx-icon icon-t-filter',
    },
    displayFields: {
      type: Array,
      default: () => [],
    },
    enableStatistics: {
      type: Boolean,
      default: true,
    },
    userConfigProps: { type: Object, default: () => ({}) },
    enableUserProfile: { type: Boolean, default: true },
    userProfileSuffix: { type: String, default: 'v1' },
    instanceCode: { type: String, default: '' },
    pageID: { type: String, default: 'fasr-popupfilter-userprofile-pageid' },
    displayMode: { type: String, default: 'tag' },
  },
  emits: Object.values(C_Emits).concat(
    TQuickFilter.emits.map(item => `${item}${C_TQuickFilter_Emits_Suffix}`),
  ),

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();
    const main = ref();
    const { t } = useI18n({ useScope: 'global' });

    onMounted(() => {
      emit(C_Emits.Init);
    });

    const profileParam = computed(() => {
      return {
        profileKeys: {
          Key: `fasr-popupfilter`,
          DynamicKey: `${props.instanceCode}_${props.userProfileSuffix}`,
        },
        PageID: props.pageID,
      };
    });

    const quickMethod = {
      setFilters(filters) {
        return publicMethod.refMasterFilter.value?.setFilters(filters);
      },
      getFilters(filters) {
        return publicMethod.refMasterFilter.value?.getFilters(filters);
      },
      querySummary() {
        publicMethod.refMasterFilter.value?.querySummary();
      },
      statisticalQuery() {
        publicMethod.refMasterFilter.value?.statisticalQuery();
      },
      query() {
        let emitArgs = { cancel: false };
        emit('filterChanged', emitArgs);
      },
      stringifyQuickFilter(advancedFilter) {
        return publicMethod.refMasterFilter.value?.stringifyQuickFilter(
          advancedFilter,
        );
      },
      getQuickFilter: advancedFilter => {
        return publicMethod.refMasterFilter.value?.getQuickFilter(
          advancedFilter,
        );
      },
      mergeAdvancedFilter: advancedFilter => {
        return publicMethod.refMasterFilter.value?.mergeAdvancedFilter(
          advancedFilter,
        );
      },
      getFilterStatement: () => {
        return publicMethod.refMasterFilter.value?.getFilterStatement();
      },
      // groupColumnStatement: computedGroupColumnStatement,
      getGroupColumnStatement: () => {
        return publicMethod.refMasterFilter.value?.getGroupColumnStatement();
      },
      getQuickFilterStatement: () => {
        return publicMethod.refMasterFilter.value?.getQuickFilterStatement();
      },
      getSummaryFilterExpression: () => {
        return publicMethod.refMasterFilter.value?.getSummaryFilterExpression();
      },
      // getGroupByFilter(advancedFilter) {},
      // wrapSummary: (quickItemSummaryRaw, Cnt = 'Total') => {
      //   // [
      //   //   { Total: mockSummary(), State: "隐藏", State2: "隐藏" },
      //   //   { Total: mockSummary(), State: "隐藏", State2: "隐藏" },
      //   //   { Total: mockSummary(), State: "CN", State2: "CN" },
      //   //   { Total: mockSummary(), State: "CN", State2: "CN" },
      //   //   { Total: mockSummary(), State: "EN", State2: "EN" },
      //   //   { Total: mockSummary(), State: "EN", State2: "EN" },
      //   // ]

      //   let keys = _.keys(_.first(quickItemSummaryRaw));
      //   _.remove(keys, k => k == Cnt);

      //   let returnValue = _.transform(
      //     keys,
      //     (rSummary, propKey) => {
      //       let groupByPropKey = _.groupBy(quickItemSummaryRaw, propKey);
      //       rSummary[propKey] = _.transform(
      //         groupByPropKey,
      //         (summary, sumValue, summaryKey) => {
      //           summary[summaryKey] = _.sumBy(sumValue, Cnt);
      //         },
      //         {},
      //       );
      //     },
      //     {},
      //   );

      //   return returnValue;

      //   // _.transform(_.groupBy(f,'State'),(r,v,k)=>{r[k]=_.sumBy(v,'Cnt')})

      //   // transform(quickItemSummaryRaw, (r, val), {});
      // },
      getQuickFilterSnapshoot() {
        return publicMethod.refMasterFilter.value?.getQuickFilterSnapshoot();
      },

      getFasDynamicFilter(filters) {
        return publicMethod.refMasterFilter.value?.getFasDynamicFilter(filters);
      },
      zipFasDynamicFilter(o, Filters) {
        return publicMethod.refMasterFilter.value?.zipFasDynamicFilter(
          o,
          Filters,
        );
      },
      getFasDynamicGroupByFilter(advancedFilter) {
        return publicMethod.refMasterFilter.value?.getFasDynamicGroupByFilter(
          advancedFilter,
        );
      },
      getSummaryFilter(advancedFilter) {
        return publicMethod.refMasterFilter.value?.getSummaryFilter(
          advancedFilter,
        );
      },
      getSummaryFields() {
        return publicMethod.refMasterFilter.value?.getSummaryFields();
      },
      // setTagMode() {
      //   mappingExpose.displayMode.value = 'tag';
      // },
      // setReactiveMode() {
      //   mappingExpose.displayMode.value = 'reactive';
      // },
      // toggleDisplayMode() {
      //   mappingExpose.displayMode.value == 'reactive'
      //     ? publicMethod.setTagMode()
      //     : publicMethod.setReactiveMode();
      // },
      // computedFilterItems,
      setSelectedItem(obj, opts = { clear: false }) {
        publicMethod.refMasterFilter.value?.setSelectedItem(obj, opts);
      },
      updateByFilter(w, opts) {
        publicMethod.refMasterFilter.value?.updateByFilter(w, opts);
      },
      getAllFilters(filters) {
        return publicMethod.refMasterFilter.value?.getAllFilters(filters);
      },
      setHelpTip(opts, val = '') {
        return publicMethod.refMasterFilter.value?.setHelpTip(opts, val);
      },
    };

    const publicMethod = {
      ...quickMethod,
      symbolDestructuring: SymbolDestructuring,
      modelValue: computed(() => modelValue),
      getGroupByFilter(args) {
        return refMasterFilter.value?.getGroupByFilter(args);
      },
      showDialog: () => {
        refDialog.value.showDialog();
      },
      closeDialog: () => {
        refDialog.value.closeDialog();
      },
      show: () => {
        publicMethod.showDialog();
      },
      setUserProfile({ displayFields = [], enableStatistics = false }) {
        mappingProps.displayFields = displayFields;
        mappingProps.enableStatistics = enableStatistics;
        enableStatisticsFlag.value = enableStatistics;
      },
      getUserProfile() {
        return {
          displayFields: mappingProps.displayFields,
          enableStatistics: mappingProps.enableStatistics,
        };
      },
      clearSelected() {
        refQuickFilter.value?.clearSelected();
      },
      reset() {
        refQuickFilter.value?.clearSelected();
        refQuickFilter.value?.setSelectedItem(modelValue.selectedValue);
      },
      refMasterFilter: computed(() => refMasterFilter.value),
      refQuickFilter: computed(() => refQuickFilter.value),
    };
    const [mappingProps, mappingExpose] = useMappingProps(props, publicMethod);

    const { getUserProfile, saveUserProfile, emitUserProfileChange } =
      useUserProfile(props, mappingProps, emit, { C_Emits, publicMethod });

    getUserProfile();

    const enableStatisticsFlag = ref(false);
    watch(
      () => props.userConfigProps,
      val => {
        publicMethod.setUserProfile(val);
      },
    );
    watch(
      () => mappingProps.userConfigProps,
      val => {
        publicMethod.setUserProfile(val);
      },
    );
    watch(
      () => mappingProps.enableStatistics,
      val => {
        if (val) {
          refMasterFilter.value?.querySummary();
        }
      },
    );
    const refDialog = ref(null);
    const dialogShow = ref(false);
    let enableStatisticsFlagDialog = false;
    const dialogFilterFields = ref();
    function emitCancel() {
      emit(C_Emits.Cancel);
      publicMethod.closeDialog();
    }
    function readerDialog() {
      return (
        <TDialog
          ref={refDialog}
          class='t-popup-filter-dialog'
          position='right'
          maximized={true}
          noBackdropDismiss={false}
          onEscapeKey={emitCancel}
          onShow={() => {
            dialogShow.value = true;
            tempDefaultFilters.value = defaultFilters.value;
            enableStatisticsFlagDialog = mappingProps.enableStatistics;
            dialogFilterFields.value = _.cloneDeep(mappingProps.filterFields);
            nextTick(() =>
              refQuickFilter.value?.setSelectedItem(modelValue.selectedValue),
            );
            // refMasterFilter.value?.setSelectedItem(modelValue.selectedValue);
            enableStatisticsFlag.value = mappingProps.enableStatistics;
          }}
          onHide={() => {
            dialogShow.value = false;
            refMasterFilter.value?.setSelectedItem(modelValue.selectedValue);
            enableStatisticsFlag.value = false;
            mappingProps.enableStatistics = enableStatisticsFlagDialog;
            refMasterFilter.value?.changeStatistics(enableStatisticsFlagDialog);
          }}
        >
          {readerDialogLayout()}
        </TDialog>
      );
    }

    const dialogLayoutStyle = computed(() => {
      return {
        height: '100%',
      };
    });

    function lang(langKey, defaultValue = '') {
      return defaultValue || _.get($q.lang?.popupFilter, langKey);
    }

    function readerDialogLayout() {
      return (
        <div class={['t-popup-filter-dialog-layout']}>
          {readerDialogHeader()}
          {readerDialogBody()}
          {readerDialogFooter()}
        </div>
      );
    }

    function readerDialogHeader() {
      let closeBtnStyle = {
        position: 'absolute',
        right: '0px',
        // top: 0,
      };
      return (
        <div class={['t-popup-filter-dialog-header']}>
          <span class={'t-popup-filter-dialog-header--title'}>{lang('title')}</span>
          <TButton
            style={closeBtnStyle}
            class='tr-button-icon-text2'
            icon='fas dx-icon icon-t-delete-01'
            showHint='true'
            tabIndex='1'
            onClick={emitCancel}
            v-close-popup
          ></TButton>
        </div>
      );
    }

    function readerDialogFooter() {
      const buttonClasses = ['t-popup-filter-dialog-footer--flex'];
      return (
        <div class={['t-popup-filter-dialog-footer']}>
          <TButton
            class={buttonClasses.concat('tr-button-default')}
            label={lang('reset')}
            showHint={true}
            onClick={onReset}
          ></TButton>
          <TButton
            class={[buttonClasses.concat('tr-button-primary')]}
            label={lang('confirm')}
            showHint={true}
            onClick={onConfirm}
          ></TButton>
        </div>
      );
    }

    function onReset() {
      // TODO
      publicMethod.reset();
    }

    const computedDefaultFilters = computed(() => {
      if (false && 0 === tempDefaultFilters.value?.length) {
        return defaultFiltersWithDesign.value;
      } else {
        return tempDefaultFilters.value;
      }
    });
    function syncModelValue(quickFilter = refQuickFilter.value) {
      debugger;
      defaultFilters.value = computedDefaultFilters.value;
      mappingProps.displayFields = computedDefaultFilters.value;
      mappingProps.enableStatistics = enableStatisticsFlag.value;
      // mappingProps.enableStatistics = enableStatisticsFlag.value;
      enableStatisticsFlagDialog = enableStatisticsFlag.value;
      modelValue.selectedValue = quickFilter?.getSelectedValue();
    }

    function onConfirm() {
      debugger;
      syncModelValue();
      refDialog.value.hide();
      nextTick(() => {
        refMasterFilter.value?.setSelectedItem(modelValue.selectedValue, {
          forceClear: true,
        });
        nextTick(() => emit(C_Emits.Confirm, modelValue));
        saveUserProfile(publicMethod.getUserProfile());
      });
      emitUserProfileChange();
    }

    function hover(isOver) {
      if (refbodyFields.value) {
        let { scrollHeight, clientHeight } = refbodyFields.value;
        const className = 't-popup-filter-dialog-body-fields--scroll';
        if (isOver && scrollHeight > clientHeight) {
          refbodyFields.value.classList.add(className);
        } else {
          refbodyFields.value.classList.remove(className);
        }
      }
    }

    const refbodyFields = ref(null);
    function readerDialogBody() {
      return (
        <div class={['t-popup-filter-dialog-body', 'tr-div-dialog']}>
          {readerToolbar()}
          <div
            ref={refbodyFields}
            class={['t-popup-filter-dialog-body-fields']}
            onMouseover={() => hover(true)}
            onMouseout={() => hover(false)}
            onTouchstart={() => { hover(true) }}
            onTouchend={() => hover(false)}
          >
            {readerQuickFilter()}
          </div>
        </div>
      );
    }

    let modelValue = reactive({
      getSelectedValue(args) {
        return refQuickFilter.value?.getSelectedValue(args);
      },
      fasDynamicFilter: null,
      getFasDynamicFilter() {
        return refQuickFilter.value?.getFasDynamicFilter();
      },
    });

    const defaultFiltersWithDesign = computed(() => {
      let outerFilter = props.filterFields.filter(f => f.isOutFilter);
      // if (outerFilter.length === 0) outerFilter = props.filterFields;
      return outerFilter.map(f => f.fieldCode);
    });

    const defaultFilters = ref(defaultFiltersWithDesign.value);
    watch(
      () => props.displayFields,
      val => {
        defaultFilters.value = val;
      },
    );
    watch(
      () => mappingProps.displayFields,
      val => {
        defaultFilters.value = val;
      },
    );
    const tempDefaultFilters = ref([]);
    const selectOpts = computed(() =>
      props.filterFields.map(item => {
        let fieldName = item.fieldName;
        let column = _.find(props.optColumns, c => {
          return (
            (c.fieldAlias || c.dataField) ==
            (item.displayFieldAlias || item.fieldAlias)
          );
        });
        if (column) {
          fieldName = column.fieldName || column.caption || fieldName;
          if (column.RefSchemaExpr) {
            fieldName = t(`${column.RefSchemaExpr}.Text`, fieldName);
          }
          if (
            column.ValueInfo_caption &&
            column.ValueInfo_caption.ReferenceExpr
          ) {
            fieldName = t(
              column.ValueInfo_caption.ReferenceExpr,
              column.caption || fieldName,
            );
          }
        }

        return { label: fieldName, value: item.fieldCode };
      }),
    );
    // watch(
    //   () => props.filterFields,
    //   () => {
    //     alert('props.filterFields');
    //     defaultFilters.value = props.filterFields.map(f => f.fieldCode);
    //   },
    // );
    function readerDefaultFilters() {
      return (
        <DefaultFilter
          v-show={false === mappingProps.hideQuickFilter}
          lang={lang}
          modelValue={defaultFilters.value}
          onUpdate:modelValue={val => (tempDefaultFilters.value = val)}
          selectOpts={selectOpts.value}
        ></DefaultFilter>
      );
    }

    const computedEnableStatisticsItems = computed(() => {
      return props.filterFields.filter(f => f.enableStatistics);
    });
    const computedEnableStatisticsFieldCode = computed(() => {
      return computedEnableStatisticsItems.value.map(f => f.fieldCode);
    });
    const computedEnableStatistics = ref(computedEnableStatisticsItems.value.length > 0);
    function readerEnableStatistics() {
      return (
        // refQuickFilter.value?.initEnableStatistics ||
        computedEnableStatistics.value && (
          <div class='t-popup-filter-enable-statistics'>
            <div class='t-popup-filter-enable-statistics-title'>
              <TLabel
                valueType='static'
                showHint='true'
                constValue={lang('showStatistics')}
              ></TLabel>
            </div>
            <TToggle
              hideLabel='true'
              helpPlacement='bottom'
              labelPosition='top'
              v-model={enableStatisticsFlag.value}
              onChange={onShowStatisticsChangeHandler}
            ></TToggle>
          </div>
        )
      );
    }
    function readerToolbar() {
      return (
        <div
          class='t-popup-filter-dialog-body-toolbar'
          style={{
            [false === computedEnableStatistics.value &&
            '--t-popup-filter-dialog-statistics-width']: '0px',
          }}
        >
          {readerDefaultFilters()}
          {readerEnableStatistics()}
        </div>
      );
    }

    const computedSelectHelper = computed(() =>
      props.filterFields.filter(
        f => FilterFieldDisplayType.SelectHelper === f.displayType,
      ),
    );

    const selectedValueWithSelectHelper = computed(() => {
      let pick = _.map(computedSelectHelper.value, 'fieldCode');
      return _.pick(modelValue?.selectedValue, pick);
    });

    function refreshSelectHelper({ qSelectedValue } = {}) {
      return; /** 帮助组件的赋值逻辑调整不需要这个操作 */
      let selectedValue = selectedValueWithSelectHelper.value;
      refQuickFilter.value?.setSelectedItem(qSelectedValue || selectedValue);
      refMasterFilter.value?.setSelectedItem(selectedValue);
    }

    let qSelectedValue;
    const statisticFlag = ref({});
    function onShowStatisticsChangeHandler() {
      qSelectedValue = refQuickFilter.value.getSelectedValue();
      statisticFlag.value = refQuickFilter.value.changeStatistics({
        enable: enableStatisticsFlag.value,
      });

      if (enableStatisticsFlag.value) emit(quickFilterEmitName('querySummary'));
      // refQuickFilter.value?.toggleStatistics();
      refreshSelectHelper({ qSelectedValue });
    }

    const computedFilterFields = computed(() => {
      return mappingProps.filterFields;
    });
    const computedOptColumns = computed(() => {
      return mappingProps.optColumns;
    });
    const computedQuickItems = computed(() => {
      return mappingProps.quickItems;
    });
    const computedQuickItemSummary = computed(() => {
      nextTick(() => {
        refreshSelectHelper({ qSelectedValue });
        qSelectedValue = null;
      });
      return mappingProps.quickItemSummary;
    });

    function quickFilterEmitName(emitName) {
      return `${emitName}${C_TQuickFilter_Emits_Suffix}`;
    }

    function onQuickFilterInitHandler() {
      emit(quickFilterEmitName('init'));
      // fasr_quick_filter_Init();
    }

    function fasr_quick_filter_Init() {
      mappingExpose.quickItems.value = _.transform(
        refQuickFilter.value?.filterItemsIsSDO,
        (result, f) => {
          result[f.fieldAlias] = [
            { label: '状态-0', value: '0' },
            { label: '状态-1', value: '1' },
            { label: '英文-2', value: '2' },
          ];
        },
        {},
      );
    }

    function mappingQuickFilterEvent(emit, emits) {
      return mappingEvent(emit, emits, C_TQuickFilter_Emits_Suffix);
    }

    const quickFilterEvent = mappingQuickFilterEvent(emit, TQuickFilter.emits);

    function onQuickFilterQuerySummaryHandler() {
      if (mappingProps.enableStatistics) {
        emit(quickFilterEmitName('querySummary'));
      }
    }
    const refQuickFilter = ref(null);
    function readerQuickFilter() {
      return (
        <TQuickFilter
          ref={refQuickFilter}
          class='t-quick-filter-columns'
          filterFields={dialogFilterFields.value}
          showSummaryCount={
            enableStatisticsFlag.value && computedEnableStatistics.value
          }
          displayMode='tag'
          optColumns={computedOptColumns.value}
          quickItems={computedQuickItems.value}
          quickItemSummary={computedQuickItemSummary.value}
          // {...quickFilterEvent}
          initQuerySummary={false}
          onInit={onQuickFilterInitHandler}
          onQuerySummary={onQuickFilterQuerySummaryHandler}
          selectHelperSearchConfig={props.selectHelperSearchConfig}
        ></TQuickFilter>
      );
    }

    function onFilterClickHandler() {
      publicMethod.showDialog();
    }
    function readerFilterButton() {
      // alert(11)
      // debugger;
      return (
        false === mappingProps.hidePopupFilter && (
          <div
            class={[
              't-popup-filter-container-navigation-filter-button',
              false == mappingProps.hideQuickFilter &&
                defaultFilters.value?.length > 0 &&
                't-popup-filter-container-navigation-filter-button--bg',
            ]}
          >
            <TButton
              class='tr-button-icon-text'
              label={lang('filter', mappingProps.filterText)}
              icon={mappingProps.filterIcon}
              showHint='true'
              show
              onClick={onFilterClickHandler}
            ></TButton>
          </div>
        )
      );
    }

    const refMasterFilter = ref(null);

    const computedMasterFilterFields = computed(() => {
      return dialogShow.value
        ? _.cloneDeep(mappingProps.filterFields)
        : computedFilterFields.value;
      // return _.filter(computedFilterFields.value, f => {
      //   return defaultFilters.value.includes(f.fieldCode);
      // });
    });

    function readerMasterQuickFilter() {
      return (
        <TQuickFilter
          ref={refMasterFilter}
          filterFields={computedFilterFields.value}
          // filterFields={computedMasterFilterFields.value}
          displayFields={defaultFilters.value}
          showSummaryCount={
            mappingProps.enableStatistics && computedEnableStatistics.value
          }
          displayMode={mappingProps.displayMode}
          optColumns={computedOptColumns.value}
          quickItems={computedQuickItems.value}
          quickItemSummary={computedQuickItemSummary.value}
          // {...quickFilterEvent}
          initQuerySummary={mappingProps.enableStatistics}
          onInit={onQuickFilterInitHandler}
          onQuerySummary={onQuickFilterQuerySummaryHandler}
          onFilterChanged={val => {
            modelValue.selectedValue =
              refMasterFilter.value?.getSelectedValue();
            emit('filterChanged', val);
          }}
          selectHelperSearchConfig={props.selectHelperSearchConfig}
        ></TQuickFilter>
      );
    }

    expose(mappingExpose);

    const leftNavBtn = ref(false);
    const rightNavBtn = ref(false);
    const leftNavBtnDisable = ref(false);
    const rightNavBtnDisable = ref(false);

    function filterContainerHoverHandler(e) {
      console.log(e);
      let { type, currentTarget, target } = e;
      let isOver = 'mouseover' === type;
      let { scrollLeft, scrollHeight, clientHeight, scrollWidth, clientWidth } =
        currentTarget;
      const className = 't-popup-filter-container--hover';
      if (isOver && scrollWidth > clientWidth) {
        // leftNavBtn.value = scrollLeft > 0;
        // rightNavBtn.value = scrollLeft + clientWidth < scrollWidth;
        leftNavBtn.value = true;
        rightNavBtn.value = true;
        currentTarget.classList.add(className);
      } else {
        leftNavBtn.value = false;
        rightNavBtn.value = false;
        currentTarget.classList.remove(className);
      }
    }
    const refPopupFilterContainer = ref();
    function leftNavBtnClickHandler() {
      debugger;
      if (refPopupFilterContainer.value) {
        refPopupFilterContainer.value.scrollLeft -= 10;
        setNavBtn(refPopupFilterContainer.value);
      }
    }
    function rightNavBtnClickHandler() {
      debugger;
      if (refPopupFilterContainer.value) {
        refPopupFilterContainer.value.scrollLeft += 10;
        setNavBtn(refPopupFilterContainer.value);
      }
    }
    function setNavBtn({
      scrollLeft,
      scrollHeight,
      clientHeight,
      scrollWidth,
      clientWidth,
    }) {
      leftNavBtnDisable.value = 0 === scrollLeft;
      rightNavBtnDisable.value =
        Math.round(scrollLeft + clientWidth) === scrollWidth;
    }
    function mutationHandler(mutationRecords) {
      for (const index in mutationRecords) {
        let {
          scrollLeft,
          scrollHeight,
          clientHeight,
          scrollWidth,
          clientWidth,
        } = refPopupFilterContainer.value;
        leftNavBtn.value = rightNavBtn.value = scrollWidth > clientWidth;
        setNavBtn(refPopupFilterContainer.value);
      }
    }
    function onWheelHandler({ deltaY, stopPropagation, preventDefault }) {
      if (refPopupFilterContainer.value) {
        refPopupFilterContainer.value.scrollLeft += deltaY;
        setNavBtn(refPopupFilterContainer.value);
      }
      let { scrollLeft, scrollHeight, clientHeight, scrollWidth, clientWidth } = refPopupFilterContainer.value;
      if (
        clientWidth != scrollWidth
        // && scrollLeft != 0 &&
        // clientWidth + scrollLeft < scrollWidth
      ) {
        //当存在滚动条时，组织页面滚动
        event?.stopPropagation?.();
        event?.preventDefault?.();
      }
      return false;
    }
    function readerLeftNavBtn() {
      return (
        leftNavBtn.value &&
        false === mappingProps.hideQuickFilter && (
          <span
            class={[
              't-popup-filter-container-nav-btn t-popup-filter-container-nav-btn-left',
              leftNavBtnDisable.value && 'disabled',
            ]}
            onClick={() => {
              leftNavBtnClickHandler();
            }}
          >
            <TIcon name='fas dx-icon icon-t-left-outlined' />
          </span>
        )
      );
    }
    function readerRightNavBtn() {
      return (
        rightNavBtn.value &&
        false === mappingProps.hideQuickFilter && (
          <span
            disable={rightNavBtnDisable.value}
            class={[
              't-popup-filter-container-nav-btn t-popup-filter-container-nav-btn-right',
              rightNavBtnDisable.value && 'disabled',
            ]}
            onClick={() => {
              rightNavBtnClickHandler();
            }}
          >
            <TIcon name='fas dx-icon icon-t-right-outlined' />
          </span>
        )
      );
    }

    return () => {
      return (
        <div
          class={['t-popup-filter']}
          style={{ '--t-popup-filter-bg-color': mappingProps.bgColor }}
          v-show={
            mappingProps.visible &&
            (false === mappingProps.hideQuickFilter ||
              false === mappingProps.hidePopupFilter)
          }
        >
          <div
            class={[
              't-popup-filter-container',
              mappingProps.hidePopupFilter &&
                't-popup-filter-container--hidePopupFilter',
            ]}
            ref={refPopupFilterContainer}
            // onMouseover={e => filterContainerHoverHandler(e)}
            // onMouseoutCapture={e => filterContainerHoverHandler(e)}
            onWheel={onWheelHandler}
            onTouchend={e => setNavBtn(refPopupFilterContainer.value)}
            v-mutation={mutationHandler}
          >
            {/* {readerLeftNavBtn()} */}
            <div
              class={'t-popup-filter-quick'}
              v-show={
                false === mappingProps.hideQuickFilter &&
                defaultFilters.value?.length > 0
              }
            >
              {readerMasterQuickFilter()}
            </div>
            <div class={'t-popup-filter-button'}>
              <div
                v-show={false}
                class='t-popup-filter-container-navigation-button'
              >
                {readerLeftNavBtn()}
                {readerRightNavBtn()}
              </div>
              {readerFilterButton()}
            </div>
          </div>
          {readerDialog()}
        </div>
      );
    };
  },
});
